package com.nuanshui.heatedloan.userinfo.service;

import com.alibaba.fastjson.JSON;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.heatedloan.constant.ServiceConstant;
import com.nuanshui.heatedloan.constant.WXOpenIdSource;
import com.nuanshui.framework.consts.TransactionManagerType;
import com.nuanshui.framework.springContext.SpringContextUtil;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.userinfo.dal.mapper.UserWeixinAccountMapper;
import com.nuanshui.heatedloan.userinfo.facade.UserService;
import com.nuanshui.heatedloan.userinfo.facade.UserWeixinAccountService;
import com.nuanshui.heatedloan.userinfo.facade.thirdlogin.ThirdUserServiceConstant;
import com.nuanshui.heatedloan.userinfo.facade.thirdlogin.ThirdUserServiceFactory;
import com.nuanshui.heatedloan.userinfo.facade.thirdlogin.WeixinThirdUserService;
import com.nuanshui.heatedloan.userinfo.facade.wechat.WeChatService;
import com.nuanshui.heatedloan.userinfo.form.BoundUserForm;
import com.nuanshui.heatedloan.userinfo.model.User;
import com.nuanshui.heatedloan.userinfo.model.UserWeixinOpenId;
import com.nuanshui.heatedloan.userinfo.model.WechatUserInfo;
import com.nuanshui.heatedloan.middleware.whatchat.util.WechatPPUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import weixin.popular.bean.sns.SnsToken;

import java.util.List;

@Service("userWeixinAccountService")
@Transactional(readOnly=true,value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
public class UserWeixinAccountServiceImpl extends CommonServiceImpl implements UserWeixinAccountService {

	private static final Logger logger = LoggerFactory.getLogger(UserWeixinAccountServiceImpl.class);
	@Autowired
	private UserWeixinAccountMapper userWeixinAccountMapper;
	@Autowired
	private UserService userService;

	@Autowired
	@Qualifier("ThirdUserServiceFactory")
	private ThirdUserServiceFactory thirdUserServiceFactory;

	@Override
	public String loadOpenIdBySource(int source) {
		
		return userWeixinAccountMapper.loadOpenIdBySource(source);
	}
	@Override
	@Transactional(value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
	public void insert(UserWeixinOpenId userWeixinOpenId) {
		
		 userWeixinAccountMapper.insert(userWeixinOpenId);
	}
	
	@Override
	public boolean isExist(String unionId) {
		Long count = userWeixinAccountMapper.countByUnionId(unionId);
		if(count == null || count<=0) return false;
		return true;
	}
	@Override
	public UserWeixinOpenId loadByOpenId(String openId) {
		
		return userWeixinAccountMapper.loadByOpenId(openId);
	}
	
	
	@Transactional(value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
	@Override
	public WechatUserInfo getWechatUserInfo(SnsToken snsToken) {

		WeixinThirdUserService service=(WeixinThirdUserService)thirdUserServiceFactory.GetThirdUserService(ThirdUserServiceConstant.WeixinUserService);

		service.updateWeixinUnionId(snsToken.getOpenid(),snsToken.getUnionid());

		User user = service.loadByUnionUser(snsToken.getUnionid());
		
		WechatUserInfo info = new WechatUserInfo();
		if (user == null) {// 账号不存在，创建新的账号
			LogUtil.info(logger, "用户不存在创建新的用户");
			//String string = WechatUtil.getWechatUserByWechatOpenId(wechat);
			String string=WechatPPUtil.getStrByOpenId(snsToken.getOpenid());
			BoundUserForm boundUserForm = JSON.parseObject(string,
					BoundUserForm.class);
			
			WeChatService weChatService=SpringContextUtil.getBean(ServiceConstant.WeChatService);
			if(weChatService!=null)
			{
				weChatService.uploadThirdUserHeadImg(boundUserForm);
			}
			String userString = JSON.toJSONString(boundUserForm);
			logger.info("创建的微信用户的信息为" + userString);		
			boundUserForm.setFrom("weixin");
			user = service.insertUser(boundUserForm);
			
			UserWeixinOpenId userWeixinOpenId = new UserWeixinOpenId();
	    	userWeixinOpenId.setOpenId(snsToken.getOpenid());
	    	userWeixinOpenId.setSource(WXOpenIdSource.PUBLIC_ACCOUNT);
	    	userWeixinOpenId.setUserId(user.getId());
	    	userWeixinOpenId.setUnionId(snsToken.getUnionid());
	    	this.insert(userWeixinOpenId);
			logger.info("用户创建成功！");
		}else {
			
			//todo:整体逻辑还不够完善
			//获取用户公众账号的openId ，如果不存在，则保存这个 openId
			boolean isExist = this.isExist(snsToken.getUnionid());
		    if(!isExist) {
		    	UserWeixinOpenId userWeixinOpenId = new UserWeixinOpenId();
		    	userWeixinOpenId.setOpenId(snsToken.getOpenid());
		    	userWeixinOpenId.setSource(WXOpenIdSource.PUBLIC_ACCOUNT);
		    	userWeixinOpenId.setUserId(user.getId());
		    	userWeixinOpenId.setUnionId(snsToken.getUnionid());
		    	this.insert(userWeixinOpenId);
		    }else  {
		    	userWeixinAccountMapper.updateWeixinOpenIdAccountUserId(snsToken.getOpenid(),user.getId(),snsToken.getUnionid());
		    }
		}

		info.setOpenId(snsToken.getOpenid());
		info.setUserId(user.getId());
		return info;
	}
		
	@Override
	public String getOpenIdByUserId(String userId) {
		return userWeixinAccountMapper.getOpenIdByUserId(userId);
	}
	
	@Override
	public List<UserWeixinOpenId> getOpenIdsByUserIds(String whereIn) {
		return  userWeixinAccountMapper.getOpenIdsByUserIds(whereIn);
	}
	
	@Override
	public List<UserWeixinOpenId> getOpenIdsByUserIds(List<String> ids)
	{
		String strIds=StringUtils.join(ids,",");
		return getOpenIdsByUserIds(strIds);
	}
}
